package com.nt.train.processor;

import com.nt.train.annotation.PCS;
import com.nt.train.annotation.PCSAutoConfig;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ClassUtils;

import java.util.*;

/**
 * https://www.cnblogs.com/756623607-zhang/p/12037291.html
 * https://my.oschina.net/gentlelions/blog/5048995
 * https://www.cnblogs.com/changxy-codest/p/15039355.html
 * @author hlf
 * @version 1.0
 * @date 2022/9/29 10:13
 */
public class PCSAutoConfigureRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        PCSBeanDefinitionScanner scanner = new PCSBeanDefinitionScanner(registry, false);
        scanner.setResourceLoader(resourceLoader);
        scanner.registerFilters();
        /**对PCS注解类的扫描 */
        scanner.addIncludeFilter(new AnnotationTypeFilter(PCS.class));

        /** 获取启动类本地包路径处理 */
        scanner.doScan(ClassUtils.getPackageName(importingClassMetadata.getClassName()));

        /** 扫描注解获取路径 ComponentScan */
//        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(ComponentScan.class.getName());
//        String[] basePackages = (String[]) annotationAttributes.get("basePackages");
//        scanner.doScan(basePackages);

        /** 通过自定义PCSAutoConfig 注解获取自定义包路径 */
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                importingClassMetadata.getAnnotationAttributes(PCSAutoConfig.class.getName()));
        String[] basePackages = attributes.getStringArray("basePackages");
        System.out.println(basePackages);

        //读取resource 对应的 application.properties 文件下配置文件中的内容
//        ResourceBundle rb = ResourceBundle.getBundle("application");
//        String items = rb.getString("className");
//        //以，分割返回字符数组
//        String[] classNames = items.split(",");

          /**扫描执行scan的目录加载 */
        //  scanner.doScan(basePackages);
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}
